import React, { useRef, useState } from 'react';
import { useFrame, useThree } from '@react-three/fiber';
import { Text, Box, Sphere, Cylinder, Cone } from '@react-three/drei';
import type { DatingProfile } from '../types';
import * as THREE from 'three';

interface Character3DProps {
  profile: DatingProfile;
  position: [number, number, number];
  onClick: () => void;
  scale?: number;
}

export const ImprovedCharacter3D: React.FC<Character3DProps> = ({
  profile,
  position,
  onClick,
  scale = 1
}) => {
  const characterRef = useRef<THREE.Group>(null);
  const [hovered, setHovered] = useState(false);
  const [clicked, setClicked] = useState(false);
  const { camera } = useThree();

  // Animation
  useFrame((state) => {
    if (characterRef.current) {
      // Gentle floating animation
      characterRef.current.position.y = position[1] + Math.sin(state.clock.elapsedTime * 0.8 + position[0]) * 0.05;
      
      // Breathing effect
      const breathScale = 1 + Math.sin(state.clock.elapsedTime * 2) * 0.02;
      characterRef.current.scale.set(scale * breathScale, scale * breathScale, scale * breathScale);
      
      // Face the camera when hovered
      if (hovered && camera) {
        characterRef.current.lookAt(camera.position);
      }
    }
  });

  const handleClick = () => {
    setClicked(true);
    setTimeout(() => setClicked(false), 200);
    console.log('Character clicked:', profile.name);
    onClick();
  };

  const handlePointerOver = () => {
    setHovered(true);
    document.body.style.cursor = 'pointer';
  };

  const handlePointerOut = () => {
    setHovered(false);
    document.body.style.cursor = 'default';
  };

  // Gender-based styling
  const isFemale = profile.gender === 'female';
  const hairColor = isFemale ? '#8B4513' : '#654321';
  const skinColor = '#FDBCB4';
  const clothingColor = isFemale ? '#FF69B4' : '#4169E1';
  const clothingAccent = isFemale ? '#FFB6C1' : '#87CEEB';

  return (
    <group 
      ref={characterRef}
      position={position}
      onClick={handleClick}
      onPointerOver={handlePointerOver}
      onPointerOut={handlePointerOut}
    >
      {/* Enhanced Body Proportions */}
      
      {/* Body - Better proportioned */}
      <Cylinder
        position={[0, 0.6, 0]}
        args={[0.18, 0.22, 0.5]}
        castShadow
      >
        <meshStandardMaterial 
          color={clothingColor}
          roughness={0.6}
          metalness={0.1}
        />
      </Cylinder>

      {/* Chest/Torso Detail */}
      <Sphere
        position={[0, 0.75, 0.15]}
        args={[0.15]}
        castShadow
      >
        <meshStandardMaterial color={clothingAccent} />
      </Sphere>

      {/* Arms - More realistic */}
      <Cylinder
        position={[-0.3, 0.7, 0]}
        args={[0.06, 0.08, 0.4]}
        rotation={[0, 0, 0.2]}
        castShadow
      >
        <meshStandardMaterial color={skinColor} />
      </Cylinder>
      <Cylinder
        position={[0.3, 0.7, 0]}
        args={[0.06, 0.08, 0.4]}
        rotation={[0, 0, -0.2]}
        castShadow
      >
        <meshStandardMaterial color={skinColor} />
      </Cylinder>

      {/* Hands */}
      <Sphere
        position={[-0.4, 0.5, 0]}
        args={[0.06]}
        castShadow
      >
        <meshStandardMaterial color={skinColor} />
      </Sphere>
      <Sphere
        position={[0.4, 0.5, 0]}
        args={[0.06]}
        castShadow
      >
        <meshStandardMaterial color={skinColor} />
      </Sphere>

      {/* Legs - Properly positioned */}
      <Cylinder
        position={[-0.1, 0.15, 0]}
        args={[0.06, 0.08, 0.3]}
        castShadow
      >
        <meshStandardMaterial color="#4B0082" />
      </Cylinder>
      <Cylinder
        position={[0.1, 0.15, 0]}
        args={[0.06, 0.08, 0.3]}
        castShadow
      >
        <meshStandardMaterial color="#4B0082" />
      </Cylinder>

      {/* Feet - On ground level */}
      <Box
        position={[-0.1, 0.02, 0.05]}
        args={[0.12, 0.04, 0.18]}
        castShadow
      >
        <meshStandardMaterial color="#2F4F4F" />
      </Box>
      <Box
        position={[0.1, 0.02, 0.05]}
        args={[0.12, 0.04, 0.18]}
        castShadow
      >
        <meshStandardMaterial color="#2F4F4F" />
      </Box>

      {/* Head - Better proportioned */}
      <Sphere
        position={[0, 1.05, 0]}
        args={[0.16]}
        castShadow
      >
        <meshStandardMaterial 
          color={skinColor}
          roughness={0.8}
          metalness={0.0}
        />
      </Sphere>

      {/* Enhanced Hair */}
      {isFemale ? (
        // Female hair - more detailed
        <>
          <Sphere
            position={[0, 1.15, -0.08]}
            args={[0.18]}
            castShadow
          >
            <meshStandardMaterial color={hairColor} roughness={0.9} />
          </Sphere>
          <Sphere
            position={[-0.12, 1.08, -0.12]}
            args={[0.14]}
            castShadow
          >
            <meshStandardMaterial color={hairColor} roughness={0.9} />
          </Sphere>
          <Sphere
            position={[0.12, 1.08, -0.12]}
            args={[0.14]}
            castShadow
          >
            <meshStandardMaterial color={hairColor} roughness={0.9} />
          </Sphere>
          {/* Hair accessories */}
          <Box
            position={[0.08, 1.18, 0]}
            args={[0.04, 0.02, 0.02]}
            castShadow
          >
            <meshStandardMaterial color="#FFD700" metalness={0.9} />
          </Box>
        </>
      ) : (
        // Male hair - shorter and neater
        <Sphere
          position={[0, 1.12, -0.05]}
          args={[0.15]}
          castShadow
        >
          <meshStandardMaterial color={hairColor} roughness={0.9} />
        </Sphere>
      )}

      {/* Enhanced Face Features */}
      {/* Eyes */}
      <Sphere
        position={[-0.06, 1.08, 0.14]}
        args={[0.02]}
        castShadow
      >
        <meshStandardMaterial color="#000000" />
      </Sphere>
      <Sphere
        position={[0.06, 1.08, 0.14]}
        args={[0.02]}
        castShadow
      >
        <meshStandardMaterial color="#000000" />
      </Sphere>

      {/* Eye whites */}
      <Sphere
        position={[-0.06, 1.08, 0.15]}
        args={[0.025]}
      >
        <meshStandardMaterial color="#FFFFFF" />
      </Sphere>
      <Sphere
        position={[0.06, 1.08, 0.15]}
        args={[0.025]}
      >
        <meshStandardMaterial color="#FFFFFF" />
      </Sphere>

      {/* Nose - more subtle */}
      <Sphere
        position={[0, 1.04, 0.16]}
        args={[0.015]}
        castShadow
      >
        <meshStandardMaterial color={skinColor} />
      </Sphere>

      {/* Mouth */}
      <Box
        position={[0, 0.98, 0.15]}
        args={[0.04, 0.01, 0.01]}
        castShadow
      >
        <meshStandardMaterial color="#DC143C" />
      </Box>

      {/* Gender-specific accessories */}
      {isFemale && (
        <>
          {/* Earrings */}
          <Sphere
            position={[-0.16, 1.05, 0]}
            args={[0.015]}
            castShadow
          >
            <meshStandardMaterial color="#FFD700" metalness={0.9} roughness={0.1} />
          </Sphere>
          <Sphere
            position={[0.16, 1.05, 0]}
            args={[0.015]}
            castShadow
          >
            <meshStandardMaterial color="#FFD700" metalness={0.9} roughness={0.1} />
          </Sphere>
          
          {/* Necklace */}
          <Cylinder
            position={[0, 0.85, 0.1]}
            args={[0.12, 0.12, 0.01]}
          >
            <meshStandardMaterial 
              color="#FFD700" 
              metalness={0.9} 
              roughness={0.1}
              transparent
              opacity={0.8}
            />
          </Cylinder>
        </>
      )}

      {/* Name display - only when hovered */}
      {hovered && (
        <group position={[0, 1.4, 0]}>
          <Text
            fontSize={0.12}
            color="#FF1493"
            anchorX="center"
            anchorY="middle"
            castShadow
          >
            {profile.name}
          </Text>
          <Text
            position={[0, -0.15, 0]}
            fontSize={0.08}
            color="#666"
            anchorX="center"
            anchorY="middle"
          >
            {profile.age}岁 • {profile.occupation}
          </Text>
        </group>
      )}

      {/* Hover Effect - Subtle glow */}
      {hovered && (
        <Sphere
          position={[0, 0.6, 0]}
          args={[0.8]}
        >
          <meshLambertMaterial
            color="#FFD700"
            transparent
            opacity={0.15}
            side={THREE.BackSide}
          />
        </Sphere>
      )}

      {/* Click Effect - Hearts */}
      {clicked && (
        <>
          {Array.from({ length: 5 }, (_, i) => (
            <Text
              key={i}
              position={[
                (Math.random() - 0.5) * 1.5,
                0.8 + Math.random() * 0.6,
                (Math.random() - 0.5) * 1.5
              ]}
              fontSize={0.15}
              color="#FF1493"
              anchorX="center"
              anchorY="middle"
            >
              💕
            </Text>
          ))}
        </>
      )}
    </group>
  );
};